package elitech.vietnam.myfashion.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.myfashion.ImageViewActivity;
import elitech.vietnam.myfashion.LoginActivity;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.config.Const;
import elitech.vietnam.myfashion.dialog.ConnectionErrorDialog;
import elitech.vietnam.myfashion.dialog.OkCancelWarnningDialog;
import elitech.vietnam.myfashion.dialog.UserInfoDialog;
import elitech.vietnam.myfashion.dialog.WarningDialog;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Comment;
import elitech.vietnam.myfashion.entites.Member;
import elitech.vietnam.myfashion.entites.Post;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.fragment.StylerFragment;
import elitech.vietnam.myfashion.utilities.Utilities;
import elitech.vietnam.myfashion.widgets.ScaleImageView;

public class StylerDetailView extends LinearLayout implements View.OnClickListener {

	private Post			mPost			= null;
	private Member			mMember;
	private MainActivity	mContext;
	private EditText		mEdComment;
	private Button			mButtonSendComment, mButtonFollow;
	private ImageButton		mButtonDetailMenu;
	private TextView		mUserName, mProfile, mCommentCount, mTxtLike, mTxtContent, mTopCommentCount, mTxtTitle;
	private ImageView		mAvatar;
	private ScaleImageView	mImage;
	private LinearLayout	mLayoutComment, mLayoutLikes;
	private boolean			isProcessing	= false;
	private boolean			isDelete		= false;
	private boolean			isMyStyle		= false;
	private int				mPostID			= -1;
	private StylerFragment	mFrag;

	public StylerDetailView(MainActivity context, StylerFragment frag, Post post, boolean myStyle) {
		super(context);
		mContext = context;
		mFrag = frag;
		mPost = post;
		mPostID = -1;
		isMyStyle = myStyle;

	}

	public StylerDetailView(MainActivity context, StylerFragment frag, int post, boolean myStyle) {
		super(context);
		mContext = context;
		mFrag = frag;
		mPostID = post;
		mPost = null;
		isMyStyle = myStyle;

	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		LoadLayout();
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
	}
	
	public void changePost(int post, boolean myStyle) {
		mPostID = post;
		mPost = null;
		isMyStyle = myStyle;
		RefreshLayout();
	}

	public void Like() {
		if (!isProcessing) {
			if (mContext.mUser == null) {
				new OkCancelWarnningDialog(mContext, mContext.getString(R.string.requestlogin)) {
					public void onOk() {
						Intent i = new Intent(mContext, LoginActivity.class);
						int mTabId = mContext.mMainPageView.mViewPager.getCurrentItem();
						mTabId = (mTabId == 2) ? 3 : (mTabId == 3) ? 5 : mTabId;
						Log.w("Shopping", "Put ReturnToTab: " + mTabId);
						i.putExtra("ReturnToTab", mTabId);
						mContext.startActivityForResult(i, MainActivity.LOGINACTIVITY);
					};
				}.show();
			} else {
				if (mPost.Liked()) {
					new OkCancelWarnningDialog(mContext, mContext.getString(R.string.unlikepost)) {
						public void onOk() {
							new CallServiceTask() {
								private int	rs	= -2;

								protected void onPreExecute() {
									isProcessing = true;
								};

								public void work() {
									try {
										rs = service.newLike(mContext.mUser.Id, mPost.Id, mPost.Liked(), 2);
									} catch (Exception e) {
										e.printStackTrace();
									}
								};

								protected void onPostExecute(Void result) {
									if (rs == -2) {
										if (!mContext.isConnectionErrorShow) {
											mContext.isConnectionErrorShow = true;
											new ConnectionErrorDialog(mContext) {
												public void TryAgain() {
													Like();
												};
											}.show();
										}
									} else if (rs == -1) {
										mPost.Likes = mPost.Likes - 1;
										mTxtLike.setText(mPost.Likes + "");
										mLayoutLikes.setBackgroundResource(R.drawable.like);
										mPost.Liked = 0;
									} else {
										mTxtLike.setText(rs + "");
										mPost.Likes = rs;
										mLayoutLikes.setBackgroundResource(R.drawable.like);
										mPost.Liked = 0;
									}
									isProcessing = false;
								};
							}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
						};
					}.show();
				} else {
					new CallServiceTask() {
						private int	rs	= -2;

						protected void onPreExecute() {
							isProcessing = true;
						};

						public void work() {
							try {
								rs = service.newLike(mContext.mUser.Id, mPost.Id, mPost.Liked(), 2);
							} catch (Exception e) {
								e.printStackTrace();
							}
						};

						protected void onPostExecute(Void result) {
							if (rs == -2) {
								if (!mContext.isConnectionErrorShow) {
									mContext.isConnectionErrorShow = true;
									new ConnectionErrorDialog(mContext) {
										public void TryAgain() {
											Like();
										};
									}.show();
								}
							} else if (rs == -1) {
								mPost.Likes = mPost.Likes + 1;
								mTxtLike.setText(mPost.Likes + "");
								mPost.Liked = 1;
								mLayoutLikes.setBackgroundResource(R.drawable.liked);
							} else {
								mTxtLike.setText(rs + "");
								mPost.Likes = rs;
								mLayoutLikes.setBackgroundResource(R.drawable.liked);
								mPost.Liked = 1;
							}
							isProcessing = false;
						};
					}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEdComment.getWindowToken(), 0);

		switch (v.getId()) {
		case R.id.styler_detail_btnSend:
			if (mEdComment.getText().length() != 0 && Utilities.checkComment(mEdComment.getText().toString())) {
				if (mContext.mUser == null) {
					Intent intent = new Intent(mContext, LoginActivity.class);
					int mTabId = mContext.mMainPageView.mViewPager.getCurrentItem();
					mTabId = (mTabId == 2) ? 3 : (mTabId == 3) ? 5 : mTabId;
					Log.w("Shopping", "Put ReturnToTab: " + mTabId);
					intent.putExtra("ReturnToTab", mTabId);
					mFrag.startActivityForResult(intent, StylerFragment.LOGINACTIVITY);
				} else
					NewComment();
			} else {
				mEdComment.setText("");
				new WarningDialog(mContext, mContext.getString(R.string.commentblank)).show();
			}
			break;

		case R.id.styler_detail_btnFollow:
			if (mContext.mUser == null) {
				Intent intent = new Intent(mContext, LoginActivity.class);
				mFrag.startActivityForResult(intent, StylerFragment.LOGINACTIVITY);
			} else if (isDelete) {
				DeletePost();
			} else if (!mMember.Followed())
				AddFollow();
			else
				UnFollow();
			break;
		case R.id.styler_detail_layBtnLike:
			Like();
			break;
		case R.id.styler_detail_imgAvatar:
			if (mMember != null)
				new UserInfoDialog(mContext, mMember).show();
			break;
		case R.id.main_delete:
			DeletePost();
			break;
		case R.id.styler_detail_imageStyle:
			Intent i = new Intent(mContext, ImageViewActivity.class);
			i.putExtra("Link", mPost.image_url);
			mContext.startActivity(i);
			break;
		}
	}

	private void LoadMemberInfo() {
		UrlImageViewHelper.setUrlDrawable(mAvatar, Const.SERVER_IMAGE_THUMB_URL + mMember.Image, R.drawable.no_avatar);
		mUserName.setText((mMember.NickName.equals("")) ? mMember.Name : mMember.NickName);
		mProfile.setText(mMember.Profile);

		if (mContext.mUser != null && mContext.mUser.Id != mMember.Id) {
			mButtonFollow.setVisibility(View.VISIBLE);
			if (mMember.Followed()) {
				mButtonFollow.setText(mContext.getString(R.string.followed));
				mButtonFollow.setBackgroundResource(R.drawable.darkblue_ovalbutton);
//				mButtonFollow.setEnabled(false);
			}
		} else if (mContext.mUser != null && mContext.mUser.Id == mMember.Id) {
			mButtonFollow.setVisibility(View.GONE);
			mButtonDetailMenu.setOnClickListener(StylerDetailView.this);
			mButtonDetailMenu.setVisibility(View.VISIBLE);
			isDelete = true;
		}
	}

	private void GetComment() {
		new CallServiceTask() {
			private ArrayList<Comment>	rs;

			public void work() {
				try {
					rs = service.getCommentOfProduct(mPost.Id, 2);
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				if (rs == null)
					return;
				mPost.Comments = rs.size();
				mCommentCount.setText(mPost.Comments + "");
				mTopCommentCount.setText(mPost.Comments + "");
				mLayoutComment.removeAllViews();
				for (int i = mLayoutComment.getChildCount(); i < rs.size(); i++) {
					CommentView comment = new CommentView(mContext, rs.get(i));
					mLayoutComment.addView(comment);
				}
				if (isDelete)
					mTopCommentCount.setVisibility(View.VISIBLE);
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void RefreshComment() {
		new CallServiceTask() {
			private ArrayList<Comment>	rs;
			public void work() {
				try {
					rs = service.getCommentOfProduct(mPost.Id, 2);
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};
			protected void onPostExecute(Void result) {
				if (rs == null)
					return;
				mPost.Comments = rs.size();
				mCommentCount.setText(mPost.Comments + "");
				for (int i = mLayoutComment.getChildCount(); i < rs.size(); i++) {
					CommentView comment = new CommentView(mContext, rs.get(i));
					mLayoutComment.addView(comment);
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void GetMember() {
		new CallServiceTask() {
			public void work() {
				try {
					int id = (mContext.mUser == null) ? -1 : mContext.mUser.Id;
					mMember = service.getInfoMemberByID(mPost.IdAccount, id);
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				if (mMember != null)
					LoadMemberInfo();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void NewComment() {
		if (!isProcessing) {
			new CallServiceTask() {
				int	rs	= 0;

				protected void onPreExecute() {
					isProcessing = true;
				};

				public void work() {
					try {
						rs = service.newComment(mPost.Id, mContext.mUser.Id, mEdComment.getText().toString(), 2);
					} catch (Exception e) {
						rs = -1;
						e.printStackTrace();
					}
				};

				protected void onPostExecute(Void result) {
					isProcessing = false;
					if (rs == -1)
						if (!mContext.isConnectionErrorShow) {
							mContext.isConnectionErrorShow = true;
							new ConnectionErrorDialog(mContext) {
								public void TryAgain() {
									NewComment();
								};
							}.show();
						}
					if (rs > 0) {
						GetComment();
						mEdComment.setText("");
						NotifyComment(rs);
					}
				};
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
	}

	private void DeletePost() {
		new OkCancelWarnningDialog(mContext, mContext.getString(R.string.deletepost)) {
			public void onOk() {
				new CallServiceTask() {
					int	rs	= 0;

					@Override
					public void work() {
						try {
							rs = service.deletePost(mPost.Id);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					protected void onPostExecute(Void result) {
						if (rs == 1) {
							Toast.makeText(mContext, R.string.deletepostsuccess, Toast.LENGTH_SHORT).show();
							mContext.onBackPressed();
						} else
							Toast.makeText(mContext, R.string.deletepostfailed, Toast.LENGTH_SHORT).show();
					};
				}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			};
		}.show();
	}

	private void AddFollow() {
		mButtonFollow.setEnabled(false);
		new CallServiceTask() {
			int	rs	= 0;

			@Override
			public void work() {
				try {
					rs = service.follow(mContext.mUser.Id, mMember.Id);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			protected void onPostExecute(Void result) {
				mButtonFollow.setEnabled(true);
				if (rs > 0) {
					mMember.Followed = 1;
					mButtonFollow.setText(mContext.getString(R.string.followed));
					mButtonFollow.setBackgroundResource(R.drawable.darkblue_ovalbutton);
					notifyFriendAdd(mContext.mUser.Id, mMember.Id);
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void UnFollow() {
		mButtonFollow.setEnabled(false);
		String mName = (!mMember.NickName.equals("") ? mMember.NickName : mMember.Name);
		new OkCancelWarnningDialog(mContext, String.format(mContext.getString(R.string.unfollowconfirm), mName)) {
			public void onOk() {
				new CallServiceTask() {
					int	rs	= 0;
					@Override
					public void work() {
						try {
							rs = service.unFollow(mContext.mUser.Id, mMember.Id);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					@Override
					protected void onPostExecute(Void result) {
						mButtonFollow.setEnabled(true);
						if (rs > 0) {
							mMember.Followed = 0;
							mButtonFollow.setText(mContext.getString(R.string.addfollow));
							mButtonFollow.setBackgroundResource(R.drawable.blue_ovalbutton);
						}
					};
				}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			};
			public void onCancel() {
				mButtonFollow.setEnabled(true);
			};
		}.show();
	}
	
	private void notifyFriendAdd(final int memId, final int followId) {
		new CallServiceTask() {
			public void work() {
				try {
					service.notifyFriendAdd(memId, followId);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					e.printStackTrace();
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void NotifyComment(final int commentID) {
		new CallServiceTask() {
			public void work() {
				try {
					service.notifyComment(commentID, 2);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					e.printStackTrace();
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void RefreshLayout() {
		new CallServiceTask() {
			public void work() {
				int accountID = (mContext.mUser == null) ? -1 : mContext.mUser.Id;
				try {
					mPost = service.getStyleByID(mPostID, accountID);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					e.printStackTrace();
				}
			};

			protected void onPostExecute(Void result) {
				if (mPost == null) {
					mContext.onBackPressed();
					return;
				}
				isMyStyle = (mContext.mUser != null && mContext.mUser.Id == mPost.IdAccount);
				if (isMyStyle) {
					if (mContext.mUser == null) {
						Intent intent = new Intent(mContext, LoginActivity.class);
						mContext.startActivityForResult(intent, MainActivity.LOGINACTIVITY);
						return;
					}
					mMember = mContext.mUser;
					LoadMemberInfo();
					// mContext.changeTitle(mContext.getString(R.string.mystyle),
					// true);
				} else {
					GetMember();
					// mContext.changeTitle(mContext.getString(R.string.styler),
					// true);
				}
				UrlImageViewHelper.setUrlDrawable(mImage, Const.SERVER_IMAGE_URL.replace("app/", "") + mPost.image_url, R.drawable.loading600);
				mCommentCount.setText(mPost.Comments + "");
				mTxtLike.setText(mPost.Likes + "");
				if (mPost.Liked())
					mLayoutLikes.setBackgroundResource(R.drawable.liked);

				mButtonSendComment.setOnClickListener(StylerDetailView.this);
				mButtonFollow.setOnClickListener(StylerDetailView.this);
				mLayoutLikes.setOnClickListener(StylerDetailView.this);
				mAvatar.setOnClickListener(StylerDetailView.this);

				GetComment();
				Timer timer = new Timer();
				timer.schedule(new TimerTask() {

					@Override
					public void run() {
						RefreshComment();
					}
				}, 15000, 15000);
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void LoadLayout() {
		new CallServiceTask() {
			private View	mMainMenu;

			public void work() {
				int accountID = (mContext.mUser == null) ? -1 : mContext.mUser.Id;
				if (mPost == null)
					try {
						mPost = service.getStyleByID(mPostID, accountID);
					} catch (IOException e) {
						e.printStackTrace();
					} catch (XmlPullParserException e) {
						e.printStackTrace();
					}
			};

			protected void onPostExecute(Void result) {
				if (mPost == null) {
					mContext.onBackPressed();
					return;
				}
				LayoutInflater inflater = LayoutInflater.from(mContext);
				if (inflater != null)
					inflater.inflate(R.layout.styler_detail, StylerDetailView.this);
				mPostID = mPost.Id;

				mUserName = (TextView) findViewById(R.id.styler_detail_txtUsername);
				mProfile = (TextView) findViewById(R.id.styler_detail_txtProfile);
				mCommentCount = (TextView) findViewById(R.id.styler_detail_txtNumberComment);
				mTxtLike = (TextView) findViewById(R.id.styler_detail_txtLikes);
				mTxtContent = (TextView) findViewById(R.id.styler_detail_txtContent);
				mTxtTitle = (TextView) findViewById(R.id.main_title);
				mAvatar = (ImageView) findViewById(R.id.styler_detail_imgAvatar);
				mImage = (ScaleImageView) findViewById(R.id.styler_detail_imageStyle);
				mLayoutComment = (LinearLayout) findViewById(R.id.styler_detail_layoutComment);
				mLayoutLikes = (LinearLayout) findViewById(R.id.styler_detail_layBtnLike);
				mEdComment = (EditText) findViewById(R.id.styler_detail_txtComment);
				mButtonSendComment = (Button) findViewById(R.id.styler_detail_btnSend);
				mButtonDetailMenu = (ImageButton) findViewById(R.id.main_delete);
				mButtonFollow = (Button) findViewById(R.id.styler_detail_btnFollow);
				mTopCommentCount = (TextView) findViewById(R.id.styler_detail_commentcount);
				mMainMenu = (LinearLayout) findViewById(R.id.main_menu);
				mMainMenu.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mContext.callMenu();
					}
				});

				if (isMyStyle) {
					if (mContext.mUser == null) {
						Intent intent = new Intent(mContext, LoginActivity.class);
						mContext.startActivityForResult(intent, MainActivity.LOGINACTIVITY);
						return;
					}
					mMember = mContext.mUser;
					LoadMemberInfo();
					mTxtTitle.setText(R.string.mystyle);
					// mContext.changeTitle(mContext.getString(R.string.mystyle),
					// true);
				} else {
					if (mMember == null)
						GetMember();
					else
						LoadMemberInfo();
					mTxtTitle.setText(R.string.styler);
					// mContext.changeTitle(mContext.getString(R.string.styler),
					// true);
				}
				UrlImageViewHelper.setUrlDrawable(mImage, Const.SERVER_IMAGE_URL.replace("app/", "") + mPost.image_url, R.drawable.loading600);
				mCommentCount.setText(mPost.Comments + "");
				mTxtLike.setText(mPost.Likes + "");

				if (mPost.Content != null && mPost.Content != "")
					mTxtContent.setText(mPost.Content);
				else
					mTxtContent.setVisibility(View.GONE);

				if (mPost.Liked())
					mLayoutLikes.setBackgroundResource(R.drawable.liked);

				mButtonSendComment.setOnClickListener(StylerDetailView.this);
				mButtonFollow.setOnClickListener(StylerDetailView.this);
				mLayoutLikes.setOnClickListener(StylerDetailView.this);
				mAvatar.setOnClickListener(StylerDetailView.this);
				mImage.setOnClickListener(StylerDetailView.this);

				GetComment();
				Timer timer = new Timer();
				timer.schedule(new TimerTask() {

					@Override
					public void run() {
						RefreshComment();
					}
				}, 15000, 15000);
				
				clearFocus();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	//
	// class DetailMenuDialog extends Dialog implements View.OnClickListener {
	//
	// public DetailMenuDialog(Context context) {
	// super(context, R.style.Dialog);
	// }
	//
	// @Override
	// protected void onCreate(Bundle savedInstanceState) {
	// super.onCreate(savedInstanceState);
	// setContentView(R.layout.dl_detailmenu);
	//
	// this.findViewById(R.id.dl_menu_delete).setOnClickListener(this);
	// }
	//
	// @Override
	// public void onClick(View v) {
	// switch (v.getId()) {
	// case R.id.dl_menu_delete:
	// DeletePost();
	// break;
	//
	// default:
	// break;
	// }
	// dismiss();
	// }
	//
	// }
}
